// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

// 云函数入口函数
exports.main = async event => {
  const { OPENID: _openid } = cloud.getWXContext()
  if (!_openid) {
    throw new Error('no openid')
  }

  let { user, phone } = event
  if (phone && phone.cloudID) {
    phone = phone.data
  }
  if (!user || !phone) {
    throw new Error('incomplete user info')
  }

  const { nickName, avatarUrl, gender } = user
  const { phoneNumber } = phone
  const data = { nickName, avatarUrl, gender, phoneNumber }

  const {
    data: [uData],
  } = await db.collection('user').where({ _openid }).get()

  if (!uData) {
    data.createAt = new Date()
    await db.collection('user').add({ data: { _openid, ...data } })
  } else {
    await db.collection('user').where({ _openid }).update({ data })
  }
}
